/* eslint-disable vue/require-default-prop */
<template>
  <div class="thermodynamic">
    <div id="container" />
    <slot />
  </div>
</template>

<script>
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
/* eslint-disable vue/require-default-prop */
import loadBMap from "../js/loadAMap"

export default {
  name: "MapGd",
  data() {
    return {
      myMap: {},
      mouseTool: {},
      infoWindow: {},
      contextMenu: {},
      markerList: []
    }
  },
  props: {
    pointList: {
      type: Array
    },
    city: {
      type: String
    },
    singlePoint: {
      type: Boolean
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getHotspot()
    })
  },
  methods: {
    // 地图初始化
    async getHotspot() {
      loadBMap(this.$ocean.AMapAK)
        .then(() => {
          // 地图实例
          this.myMap = new AMap.Map("container")
          this.switchCity(this.city || '北京')
          // 信息窗口实例
          this.infoWindow = new AMap.InfoWindow({
            anchor: "top-center",
          })
          // 地理编码
          this.geocoder = new AMap.Geocoder({
              // city: "010", //城市设为北京，默认：“全国”
              radius: 1000 //范围，默认：500
          })
          // 鼠标工具插件
          this.mouseTool = new AMap.MouseTool(this.myMap)
          this.mouseTool.on("draw", (e) => {
            this.overlaycomplete(e)
          })
          // 绘制默认点
          if(this.pointList.length > 0) {
            this.pointList.map(async item => {
              this.addPoint(item)
            })
          }
        })
        .catch((err) => {
          console.log('异步加载失败：', err)
        })
    },
    // 切换城市
    switchCity(city) {
      this.myMap.setCity(city)
    },
    // 坐标系转换
    coordinateTranslate(point) {
      return new Promise((resolve, reject) => {
        if (point.coordinateType === 2) return resolve(point)
        let type = point.coordinateType === 3 ? 'baidu' : 'gps'
        AMap.convertFrom([point.lng, point.lat], type, (status, result) => {
          if(result.info === 'ok') {
            let p = result.locations[0]
            let i = this.$ocean.deepClone(point)
            i.lng = p.lng
            i.lat = p.lat
            i.coordinateType = 2
            i.pointId = point.pointId
            resolve(i)
          } else {
            console.log('坐标转换失败')
            reject(result)
          }
        })
      })
    },
    // 鼠标工具添加完点的回调
    overlaycomplete(e) {
      if(this.singlePoint) {
        this.markerList.map(item => {
          this.deletePoint(item)
        })
        this.markerList = []
      }
      e.obj.pointId = new Date().getTime()
      this.$nextTick(() => {
        this.pointFun(e.obj)
        // 添加到点列表
        let pointList = this.$ocean.deepClone(this.pointList)
        pointList.push({
          lng: e.obj.getPosition().lng,
          lat: e.obj.getPosition().lat,
          pointId: e.obj.pointId,
          coordinateType: 2
        })
        this.$emit('update:pointList', pointList)
        this.markerList.push(e.obj)
      })
    },
    // 配置点功能
    pointFun(el) {
      // 添加点击事件
      el.on("click", (e) => {
        this.openInfo(el)
      })
      // 添加拖拽中事件
      el.on("dragging", (e) => {
        this.infoWindow.close()
        // this.openInfo(el)
      })
      // 添加拖拽结束事件
      el.on("dragend", (e) => {
        this.deitPoint(el)
      })
      // 添加右键菜单
      el.on("rightclick", () => {
        //创建右键菜单
        let contextMenu = new AMap.ContextMenu()
        contextMenu.addItem("删除", () => {
          this.deletePoint(el)
        }, 0)
        contextMenu.open(this.myMap, el.getPosition());
      })
    },
    // 配置中心点及缩放级别
    async setCenterZoom(option) {
      // 设置中心点
      if (option.center) {
        let point = await this.coordinateTranslate(option.center)
        console.log([point.lng,point.lat])
        this.myMap.setCenter([point.lng,point.lat])
      }
      // 设置缩放级别
      if (option.zoom) {
        this.myMap.setZoom(option.zoom)
      }
    },
    /**
     * 获取点详细地址
     * @param {Object} point - 坐标点信息
     * @param {number} point.lng - 经度
     * @param {number} point.lat - 纬度
     * @param {number} point.coordinateType - 坐标系类型
     */ 
    async getAddress(point) {
      point = await this.coordinateTranslate(point)
      return new Promise((resolve, reject) => {
        this.geocoder.getAddress([point.lng, point.lat], (status, result) => {
          if (status === 'complete'&&result.regeocode) {
            let info = result.regeocode
            resolve(Object.assign({
              formattedAddress: info.formattedAddress,// 完整地址
              adcode: info.addressComponent.adcode,// 邮政编码
              citycode: info.addressComponent.citycode,// 固定电话区号
              district: info.addressComponent.district,// 区
              province: info.addressComponent.province,// 省
              city: info.addressComponent.city,// 市
              street: info.addressComponent.street,// 街道
              streetNumber: info.addressComponent.streetNumber, // 街道号
              township: info.addressComponent.township,// 镇
            },point))
          }else{
            console.log('获取详细地址失败')
            reject(result)
          }
        })
      })
    },
    /**
     * 新增点
     */ 
    async addPoint(el){
      el = await this.coordinateTranslate(el)
      let marker = new AMap.Marker({
        position: [el.lng, el.lat],
        draggable: true 
      })
      marker.pointId = el.pointId
      this.pointFun(marker)
      marker.setMap(this.myMap)
      this.markerList.push(marker)
    },
    // 修改点
    deitPoint(el){
      let pointList = this.$ocean.deepClone(this.pointList)
      let point = el.getPosition()
      pointList.map((item, index) => {
        if(el.pointId === item.pointId) {
          item.lng = point.lng
          item.lat = point.lat
          item.coordinateType = 2
        }
      })
      this.$emit('update:pointList', pointList)
    },
    // 删除点
    deletePoint(el) {
      this.myMap.remove(el)
      let pointList = this.$ocean.deepClone(this.pointList)
      pointList.map((item, index) => {
        if(el.pointId === item.pointId) {
          pointList.splice(index,1)
        }
      })
      this.$emit('update:pointList', pointList)
      this.markerList.map((item, index) => {
        if(el.pointId === item.pointId) {
          this.markerList.splice(index,1)
        }
      })
    },
    // 展示信息
    openInfo(e) {
      let position = [e.getPosition().lng, e.getPosition().lat]
      this.infoWindow.setContent(
        "该点坐标<br/>经度：" +
          e.getPosition().lng +
          "<br/>纬度：" +
          e.getPosition().lat
      )
      this.infoWindow.open(this.myMap, position)
    },
    // 返回地图信息
    getMapInfo() {
      let zoom = this.myMap.getZoom()
      let center = this.myMap.getCenter()
      center = {
        lat: center.lat,
        lng: center.lng,
        coordinateType: 2
      }
      return { zoom, center }
    },
    // 清空覆盖物
    clearOverlay() {
      this.myMap.clearMap()
    },
    // 工具-拖动
    drag() {
      this.mouseTool.close()
    },
    // 工具-画点
    drawSome() {
      this.mouseTool.marker({ draggable: true })
    },
  },
}
</script>

<style lang="scss" scoped>
.thermodynamic {
  width: 100%;
  height: 100%;
  #container {
    width: 100%;
    height: 100%;
  }
}
</style>
